<template>
  <div v-loading="loading" class="edit-user-info">
    <div class="head">
      <span class="text">个人信息</span>
    </div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      label-width="80px"
      class="d-flex flex-wrap"
    >
      <el-form-item
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.field"
        :label="item.label"
      >
        <div v-if="item.type !== 'select'">
          <el-input
            v-model="form[item.field]"
            :maxlength="30"
            :disabled="item.disabled"
            clearable
          />
          <p v-if="item.field == 'wechat'" class="w_chat">
            微信号是6到20个字母、数字、下划线和减号组成的
          </p>
        </div>
        <el-select v-else v-model="form[item.field]">
          <el-option
            v-for="option in item.setting"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="wechatCodeUrl" label="微信二维码">
        <UploadImg
          :fileSize="1"
          v-model="form.wechatCodeUrl"
          :load="loading"
          @changeLoadings="changeLoadings"
          @imgChange="imgChange"
        ></UploadImg>
        <p class="w_chat" v-if="form.wechatCodeUrl" style="margin-top:-24px">请上传png/jpg/jpeg图片格式文件，大小不超过1M</p>
        <p class="w_chat"  v-else>请上传png/jpg/jpeg图片格式文件，大小不超过1M</p>
      </el-form-item>
    </el-form>
    <div class="footer-btn">
      <el-button @click="initData">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script>
import {
  adminUsersUpdateImgAPI,
  adminUsersUpdateAPI,
} from "@/api/user/personCenter";
import { mapGetters } from "vuex";
import { regexIsCRMMobile, regexIsCRMEmail } from "@/utils";
import UploadImg from "@/views/admin/merchant/components/UploadImg";

export default {
  name: "EditUserInfo",
  components: {
    UploadImg,
  },
  data() {
    const sexMap = [
      { label: "请选择", value: 0 },
      { label: "男", value: 1 },
      { label: "女", value: 2 },
    ];
    const validateCRMMobile = (rule, value, callback) => {
      if (!value || value == "" || regexIsCRMMobile(value)) {
        callback();
      } else {
        callback(new Error("手机格式有误"));
      }
    };
    const validateCRMEmail = (rule, value, callback) => {
      if (!value || value == "" || regexIsCRMEmail(value)) {
        callback();
      } else {
        callback(new Error("邮箱格式有误"));
      }
    };
    // const validateWxNumber = (rule, value, callback) => {
    //   if (!value || value == "" || regexIsCRMWxNum(value)) {
    //     callback();
    //   } else {
    //     callback(new Error("微信号有误"));
    //   }
    // };
    return {
      fieldList: [
        { label: "姓名", field: "realname" },
        { label: "手机号", field: "username", disabled: true },
        { label: "直属上级", field: "parentName", disabled: true },
        { label: "性别", field: "sex", type: "select", setting: sexMap },
        { label: "邮箱", field: "email" },
        { label: "部门", field: "deptName", disabled: true },
        { label: "角色", field: "roleName", disabled: true },
        { label: "微信号", field: "wechat" },
      ],
      rules: {
        realname: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        email: [{ validator: validateCRMEmail, trigger: "change" }],
        // wechat: [{ validator: validateWxNumber, trigger: "change" }],
        // username: [
        //   { required: true, message: "请填写姓名", trigger: "blur" },
        //   { validator: validateCRMMobile, trigger: "change" }
        // ]
      },
      form: {},
      loading: false,
      ewmImg: "",
      wechatDownUrl: "",
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    userInfo: {
      handler() {
        this.initData();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    changeLoadings(type) {
      this.loading = type;
    },
    imgChange(e) {
      if (e.url) {
        this.wechatDownUrl = e.url;
      } else {
        this.wechatDownUrl = "";
      }
    },
    initData() {
      this.form = Object.assign({}, this.userInfo);
    },
    handleChangeAvatar() {
      document.getElementById("inputFile").click();
    },
    /**
     * 图片操作
     * @param event
     */
    uploadFile(event) {
      const files = event.target.files;
      const file = files[0];
      const reader = new FileReader();
      const self = this;
      reader.onload = function (e) {
        let result;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          result = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          result = e.target.result;
        }
        self.editImage = result;
        self.editFile = file;
        self.showEditImage = true;
        e.target.value = "";
      };
      reader.readAsDataURL(file);
    },
    /**
     * 上传提交头像修改
     * @param data
     */
    submitImage(data) {
      this.loading = true;
      const param = new FormData();
      param.append("userId", this.form.userId);
      param.append("file", data.blob, data.file.name);
      adminUsersUpdateImgAPI(param)
        .then(() => {
          this.loading = false;
          this.$emit("change");
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * 个人信息编辑
     */
    handleSave() {
      const params = {
        realname: this.form.realname,
        sex: this.form.sex,
        email: this.form.email,
        roleName: this.form.roleName,
        username: this.form.username,
        wechat: this.form.wechat,
        wechatCodeUrl: this.form.wechatCodeUrl,
        wechatDownUrl: this.wechatDownUrl,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          adminUsersUpdateAPI(params)
            .then(() => {
              this.loading = false;
              this.$message.success("保存成功");
              this.$emit("change");
              this.$store.dispatch("initUserList");
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "./style";
.edit-user-info {
  width: 100%;
  background-color: white;
  padding: 22px 25px;
  .footer-btn {
    padding: 16px 0px;
    border-top: 1px solid #e5e5e5;
    text-align: right;
  }
}
.w_chat {
  font-size: 12px;
  color: #f56c6c;
  margin-top: -6px;
}
</style>
